#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<limits.h>

const int MOD_VAL = INT_MAX;

int main(int argc, char *argv[])
{
	int j, i, temp = 0;
	int N, k, d, num;
	char c[60];
	int *fd;
	int rand_num;

	if(argc < 3)
	{
		printf("enter 2 args:\n./randomN <N> <k>\n");
		return 0;
	}

	N = atoi(argv[1]);
	k = atoi(argv[2]);
	
	if(k > 1024)
	{
		printf("Enter k < 1024\n");
		return 0;
	}

	fd = (int *) malloc(sizeof(int) * k);

	srand( time(NULL) );

	while(temp < k)
	{
		sprintf(c, "data/%d-file.data", temp);
		fd[temp] = open(c, O_CREAT | O_RDWR, 0777);
		temp++;
	}

	num = (N+k-1)/k;
	temp = 0;

	while(temp < k)
	{
		for(j = 0; j < num; j++)
		{
			rand_num = rand() % MOD_VAL;	
			if(write(fd[temp], &rand_num, sizeof(int)) == -1)
			{
				perror("write failed\n");
			}
		}

		temp++;
	}

	temp = 0;

	while(temp < k)
	{
		if(close(fd[temp]) == -1)
		{
			printf("Coudln't close %d\n", temp);
			return 0;
		}

		temp++;
	}

	free(fd);

	return 0;
}
